<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs  v-model="activeName">
          <!-- 左侧 -->
          <el-tab-pane label="角色管理" name="role">
            <!-- 按钮 -->
            <el-button type="primary" @click="settingAdd">
              <el-icon>
                <Plus />
              </el-icon>新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="roleObj?.rows" >
              <el-table-column label="序号" width="100" type="index" :index="indexMethod"  />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button type="success" @click="settingLimits(row.id)">分配权限</el-button>
                  <el-button type="primary" @click="settingEdit(row.id)">编辑</el-button>
                  <el-button type="danger" @click="settingDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pager" style="margin-top:10px;display:flex;justify-content:flex-end;">
              <el-pagination />
            </div>
          </el-tab-pane>

          <el-tab-pane label="公司信息" name="company">
      <!-- 警告信息 -->
      <el-alert title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改" type="info" show-icon :closable="false" />
      <!-- 表单 -->
      <el-form label-width="120px" style="margin-top:50px">
        <el-form-item label="公司名称">
          <el-input disabled style="width:400px" :value="companyInfo?.name" />
        </el-form-item>
        <el-form-item label="公司地址">
          <el-input disabled style="width:400px" :value="companyInfo?.companyAddress" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input disabled style="width:400px" :value="companyInfo?.mailbox" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" :rows="3" disabled style="width:400px" :value="companyInfo?.remarks" />
        </el-form-item>
      </el-form>
</el-tab-pane>
        </el-tabs>
      </el-card>

       <!-- 分页 pagination -->
       <div class="pager" style="display:flex;justify-content:center;" v-if="activeName==='role' && roleObj?.total>0">
          <el-pagination 
            v-model:current-page="params.page" 
            v-model:page-size="params.pagesize" 
            layout=" prev, pager, next" 
            :total="roleObj?.total||0" 
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
      </div>

      <!-- 添加角色弹框 -->
      <el-dialog :title="title" v-model="isVisible" @close="handleClose" close-on-click-modal="false">
          <el-form label-width="100px" :model="formData" :rules="rules" ref="ruleForm">
              <el-form-item label="角色名称" prop="name">
                  <el-input placeholder="请输入角色名称" v-model="formData.name" />
              </el-form-item>
              <el-form-item label="角色描述" prop="description">
                  <el-input placeholder="请输入角色描述" v-model="formData.description" />
              </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="settingSubmit">确定</el-button>      
            </span>
          </template>
      </el-dialog>
      
    </div>
  </div>
</template>

<script lang="ts" setup>
// @ts-ignore
import {getRoleListApi, deleteRoleApi, addRoleApi, getRoleDetailApi, updateRoleApi, getCompanyInfoApi} from '@/api/setting'
import type {Roles, RoleObj, RolesParams, AddRoleParams} from '@/types/setting'
import { ref, onMounted } from 'vue'
// @ts-ignore
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
import { useUserStore } from '@/store/user';

const { userInfo } = useUserStore()
//tabs 点击的每一项
const activeName = ref('role')
// 定义角色列表数据
const roleObj = ref<RoleObj>()
// 定义请求参数
const params = ref<RolesParams>({
  page: 1,
  pagesize: 10
})

// 获取角色列表
const getRoleList =  async() => {
  const res =  await getRoleListApi(params.value)
  roleObj.value = res.data
}

// 删除员工
const settingDel = async (id: string) => {
  console.log(id)
  // 提示用户是否确认删除
  await ElMessageBox.confirm('是否确认删除该员工？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteRoleApi(id)
  // 删除成功
  ElMessage.success('删除成功')
  // 刷新列表
  getRoleList()
}

// 新增员工
const settingAdd = () => {
  title.value = '新增角色'
  handleOpen('')
}

// 编辑员工
const settingEdit = (id: string) => {
  title.value = '编辑角色'
  handleOpen(id)
}

// 分配权限
const settingLimits = (id: string) => {
  console.log(id)
}

//展示序号
const indexMethod = (index: number) => {
  return (params.value.page - 1) * params.value.pagesize + index + 1
}

//页容量变化
const handleSizeChange = (val: number) => {
  params.value.pagesize = val
  getRoleList()
}
// 页码变化
const handleCurrentChange = (val: number) => {
  params.value.page = val
  getRoleList()
}

// dialog 弹层组件显示和隐藏
const isVisible = ref(false)
const title = ref('新增角色')
// 定义dialog表单数据
const formData = ref<AddRoleParams>({
  name: '',
  description: ''
})
// 定义表单实例
const ruleForm = ref<FormInstance>()
// 定义表单验证规则
const rules = ref({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ]
})

// 打开弹框
// 获取角色详情
const roleDetial = ref<Roles>()
const handleOpen = async(id: string) => {
  isVisible.value = true
  if (id) {
    // 编辑
    // 获取角色详情
  const res =  await getRoleDetailApi(id)
  roleDetial.value = res.data
  formData.value.name = res.data.name
  formData.value.description = res.data.description
  } else {
    // 新增
    formData.value = {
      name: '',
      description: ''
    }
  }
}


// 关闭弹框
const handleClose = () => {
  isVisible.value = false
  // 重置表单
  ruleForm.value?.resetFields()
  formData.value = {
    name: '',
    description: ''
  }
}

// 提交表单
const settingSubmit = async() => {
  // 表单校验
  await ruleForm.value?.validate()
    // 判断新增还是编辑
    if (title.value === '新增角色'){
      params.value.page = Math.ceil(roleObj.value.total + 1 / params.value.pagesize)
      await addRoleApi(formData.value)
      ElMessage.success('新增成功')
    } else {
      await updateRoleApi(formData.value)
      ElMessage.success('编辑成功')
    }
    // 关闭弹框
    handleClose()
    // 刷新列表
    getRoleList()
}

// 公司模块 渲染
const companyInfo = ref<CompanyInfo>()
const getCompanyInfo = async () => {
  const res = await getCompanyInfoApi(userInfo?.companyId as string)
  companyInfo.value = res.data
}


onMounted(() => {
  getRoleList()
  getCompanyInfo()
})
</script>